 
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class MyTray extends JFrame {
    public static Frame frame;
    public MyTray(){
        frame=this;//将当前窗口赋值
    }
    public static void main(String[] args) {
        SystemTrayInitial();
    }
    //初始化菜单
    private static void SystemTrayInitial() {
        if (!SystemTray.isSupported()) {//判断系统是否支持托盘
            return;
        }
        try {
            String title = "建行项目测试demo";//系统栏通知标题
            String company = "ccb-kylin2203";//系统通知栏内容
            SystemTray systemTray = SystemTray.getSystemTray();//获取系统默认托盘
            Image image = Toolkit.getDefaultToolkit().getImage(
                    MyTray.class.getResource("logo.png"));//系统栏图标
            TrayIcon trayIcon = new TrayIcon(image, title + "\n" + company, createMenu());//添加图标,标题,内容,菜单
            trayIcon.setImageAutoSize(true);//设置图像自适应
            trayIcon.addActionListener(new SysActionListener());//双击打开窗口
            systemTray.add(trayIcon);//添加托盘
            trayIcon.displayMessage(title, company, TrayIcon.MessageType.INFO);//弹出一个info级别消息框
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
    //托盘中的菜单
    private static PopupMenu createMenu(){
        PopupMenu menu = new PopupMenu();//创建弹出式菜单
        MenuItem exitItem = new MenuItem("退出");//创建菜单项
        exitItem.addActionListener(new ActionListener(){//给菜单项添加事件监听器，单击时退出系统
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
 
            }
        });
        MenuItem openItem = new MenuItem("退出");//创建菜单项
        openItem.addActionListener(new ActionListener(){//给菜单项添加事件监听器，单击时打开系统
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
 
            }
        });
        menu.add(openItem);//添加打开系统菜单
        menu.addSeparator();//菜单分割符
        menu.add(exitItem);//添加退出系统菜单
        return menu;
    }
    //双击托盘弹出主窗体
    static class SysActionListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            frame.setVisible(true);//显示当前窗口
            frame.toFront();//将此窗口置于前端
        }
    }
}
